#include "SystemUtils.h"

char SystemUtils::getChar()
{
    char buf = 0;
    struct termios old = {0};
    fflush(stdout);
    if (tcgetattr(0, &old) < 0)
        perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if (tcsetattr(0, TCSANOW, &old) < 0)
        perror("tcsetattr ICANON");
    if (read(0, &buf, 1) < 0)
        perror("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if (tcsetattr(0, TCSADRAIN, &old) < 0)
        perror("tcsetattr ~ICANON");
    return buf;
}

int SystemUtils::inputNumber()
{
    int choice = -1;
    std::cin >> choice;
    while (std::cin.fail())
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cin >> choice;
    }
    return choice;
}

void SystemUtils::waitInput()
{
    std::cout << "请按任意键继续.." << std::endl;

    // 等待用户按键
    SystemUtils::getChar();

    // 清屏
    system("clear");
}

std::string &SystemUtils::getPassword(std::string &password)
{
    char ch;
    while ((ch = SystemUtils::getChar()) != '\n')
    {
        password.push_back(ch);
        std::cout << '*'; // 显示'*'代替输入的字符
    }
    return password;
}
